package com.chenfan.mcn.extension.rule;

import lombok.SneakyThrows;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 可计算规则引擎
 *
 * @author wulg
 * @date 2021-09-17
 **/
public class ComputableRuleEngine {

    private static Map<Class<? extends ComputableRule>, ComputableRule> mappers = new ConcurrentHashMap<>(8);

    /**
     * 注册规则
     * @param ruleClass
     */
    @SneakyThrows
    public static synchronized  <T extends ComputableRule>  void register(Class<T> ruleClass) {
        if(!mappers.containsKey(ruleClass)) {
            mappers.put(ruleClass, ruleClass.newInstance());
        }
    }

    /**
     * 触发规则
     * @param ruleClass
     * @param fact
     * @param <P>
     * @param <R>
     * @return
     */
    public static <T extends ComputableRule,P,R> R fire(Class<T> ruleClass , P fact) {
        if(!mappers.containsKey(ruleClass)) {
            register(ruleClass);
        }
        return (R) mappers.get(ruleClass).execute(fact);
    }
}
